import { Article } from 'list-model.js';
var article = new Article();

Page({

  data: {

    page:1,
    loadingHidden: false,
    searchLoading: false,
    searchLoadingComplete: false,
    currentMenuIndex:0,
    finish:false,
    
  },

  onLoad: function (options) {    
    this._loadData();
  },

  _loadData: function () {
    var that = this;
    //获得广告区信息
    article.getGuanggaoData((data) => {
      that.setData({
        guangaoArr: data.items,
      });
    });

    //获取新闻分类及初始化分类列表
    article.getCategoryData((res) => {
      that.setData({
        newsCategoryData: res.items,
        articleListData: res.items[0].data,
        loadingHidden: true,
      });
      if (res.items[0] && res.items[0].data&&res.items[0].data.length < 10) {
        that.setData({
          searchLoading: false,
          searchLoadingComplete: true,
        });
      }
    });

  },


  /*切换新闻分类*/
  changeNewsCategory: function (event) {
    var that = this,
      index = article.getDataSet(event, 'index'),
      id = article.getDataSet(event,'id');
    var listData = new Array();
    var listDatas = "";
    that.setData({
      currentMenuIndex: index,
    });
    var newsCategoryData = this.data.newsCategoryData
    for (var i = 0; i < newsCategoryData.length; i++) {
        if (index == i) {
          listData[i+1] = newsCategoryData[index].data;
          listDatas = listData[i + 1]
        }
        that.setData({
          articleListData: listDatas,
          searchLoading: false,
          searchLoadingComplete: false,
        });
      }
    if (listDatas&&listDatas.length<10){
      that.setData({
        searchLoading: false,
        searchLoadingComplete: true,
      });
    }
  },

  //触底滚动加载
  onReachBottom: function () {
    var page = parseInt(this.data.page) + 1;
    if (this.data.finish == false) {
      this.setData({
        searchLoading: true,
      })
      var id = this.data.newsCategoryData[this.data.currentMenuIndex].id;
      article.getNewsMoreData(id,page,(res) => {
        if (res[0].data&&res[0].data.length==0){
          this.setData({
            finish:true,
            searchLoading: false,
            searchLoadingComplete: true,
          })
        }else{
          this.scrollLoadData(res, page);
        }
         
      })
    }else{
      this.setData({
        searchLoading: false,
        searchLoadingComplete: true,
      })
    }
    
  },
  //拼接数据
  scrollLoadData: function (res, page) {
    var data = res[0].data;
    var articleListData = this.data.articleListData;
    articleListData = articleListData.concat(data)
    this.setData({
      articleListData: articleListData,
      page: page,
    })

  },

  //跳转到新闻详情
  toArticleDetail: function (event) {
    var id = article.getDataSet(event,'id')
    wx.navigateTo({
      url: '../article/detail?id='+id
    })
  }

})